<script>
	import i18n from "./lang/index.js";
	import {
		db
	} from '@/utils/sqlite';
	import sqliteSQL from "@/utils/sqliteSQL";

	import {
		genTestUserSig,
		aegisID
	} from "./pages/TUIKit/debug/index.js";
	import store from './store/index';
	// import {
	// 	number
	// } from "echarts";
	// v2.22.0 起支持 uni-app 打包 native app 时使用离线推送插件
	// 请注意！应合规要求，在用户同意隐私协议的前提下，登录成功后 SDK 会通过推送插件获取推送 token，并将推送 token 传递至后台（若获取 token 失败则会导致离线推送无法正常使用

	

	//用户信息
	const userInfo = uni.getStorageSync('userInfo')

	const config = {
		userID: "326505126464", //User ID
		SDKAppID: 1400533671, // Your SDKAppID
		secretKey: "aa636889f03251263f4820ab943441f10e056b7d85d23890b1f10beb09c6a00c", // Your secretKey
		// userID: "178121874911301", //User ID 测试环境
		// SDKAppID: 1400533667, // Your SDKAppID
		// secretKey: "ed6a47bc91bc6cc226580a2950f280c0f073b0484bc4bd07e1e9094aef023095",
	};
	uni.$chat_SDKAppID = config.SDKAppID;
	export default {
		data() {
			return {
				userSig: '',
				register_id: '',
				timer: null,
				updateWords: {
					'tips': '更新提示',
					'new': '发现新版本 ',
					'isUpdate': ' 是否更新？',
					'confirmText': '立即更新',
					'cancelText': '暂不更新',
					'prepare': '正在准备环境，请稍后',
					'download': '下载中',
					'connected': '已连接到服务器',
					'success': '下载成功',
					'failed1': '更新失败-01',
					'failed2': '更新失败-02',
					'failed3': '更新失败-03',
				}
			}
		},
		onLaunch: function() {
			
			
			// this.timer = setInterval(() => {
				
			// 	const value = uni.getStorageSync('first_load');
			// 	if (!value) {
			// 		uni.getNetworkType({
			// 			success: function(res) {
			// 				if (res.networkType != 'none') {
			// 					clearInterval(this.timer);
			// 					uni.reLaunch({
			// 						url: '/pages/home/index'
			// 					});
			// 				} else {
								
			// 				}
			// 			},
			// 		});
			// 	} else {
			// 		clearInterval(this.timer);
			// 	}
			// }, 2000);
			
			
		
			// 初始化本地 SQLite 表
			// this.initSQLiteCreateTable();

			//检查版本更新
			// this.checkUpdate();

			//是否有未读消息通知(好友申请)
			this.$http.get('/msg/system/count', {
				type: 2
			}).then(res => {
				if (res > 0) {
					uni.setStorageSync('notidyMsgRedStatus', true);
				}
			});

			//更新消息通知红点状态
			// this.changeNotidyRedStatus();

			//根据手机语言设置语言
			let lang = this.$store.state.vuex_user.lang || 0;
			if (lang == 0) {
				this.changLang();
			}

		},
		onShow: function() {
			
			let lang = this.$store.state.vuex_user.lang || 0;
			if (lang == 0) {
				this.changLang();
			}
			setTimeout(() => {
				this.checkArguments()
			}, 500)
		},
		onBackPress() {
			console.log("点击了饭回")
			return false
		},
		onHide: function() {},
		methods: {
			loginTIM() {
				// console.log("config.userID++++++++++++++++++++++++++++++++++++++++++" + config.userID)
				let userSig = this.userSig;
				// login TUIKit
				uni.$TUIKit.login({
					userID: config.userID,
					userSig
				}).then((res) => {
					// sdk 初始化，当 sdk 处于ready 状态，才可以使用API，文档
					uni.showLoading({
						title: "初始化...",
					});
				});

			},
			bindTIMEvent() {
				uni.$TUIKit.on(uni.$TIM.EVENT.SDK_READY, this.handleSDKReady);
				uni.$TUIKit.on(uni.$TIM.EVENT.SDK_NOT_READY, this.handleSDKNotReady);
				uni.$TUIKit.on(uni.$TIM.EVENT.KICKED_OUT, this.handleKickedOut);
			},
			// sdk ready 以后可调用 API
			handleSDKReady(event) {
				uni.$chat_isSDKReady = true
				uni.setStorageSync('$chat_SDKReady', true);
				uni.hideLoading();

				// console.log("this.userSig", this.userSig)

				// TUICallKit loginss
				uni.$TUICallKit.login({
					SDKAppID: uni.$chat_SDKAppID, // 开通实时音视频服务创建应用后分配的 SDKAppID
					userID: config.userID, // 用户 ID，可以由您的帐号系统指定
					userSig: this.userSig, // 身份签名，相当于登录密码的作用
				}, (res) => {
					if (res.code === 0) {

						uni.$TUICallKit.enableFloatWindow(true); // 开启小浮窗
					} else {
						uni.showToast({
							title: `login failed, error message = ${res.msg}`,
							duration: 2000
						});

					}
				});
			},
			handleSDKNotReady(event) {

			},

			handleKickedOut(event) {
				uni.clearStorageSync();
				uni.showToast({
					title: `${this.kickedOutReason(event.data.type)}被踢出，请重新登录。`,
					icon: "none",
				});
			},
			kickedOutReason(type) {
				switch (type) {
					case uni.$TIM.TYPES.KICKED_OUT_MULT_ACCOUNT:
						return "由于多实例登录";
					case uni.$TIM.TYPES.KICKED_OUT_MULT_DEVICE:
						return "由于多设备登录";
					case uni.$TIM.TYPES.KICKED_OUT_USERSIG_EXPIRED:
						return "由于 userSig 过期";
					case uni.$TIM.TYPES.KICKED_OUT_REST_API:
						return "由于 REST API kick 接口踢出";
					default:
						return "";
				}
			},

			subscribeGoeasy() {
				let uid = this.vuex_user.uid || 0;
				console.log("this.goEasy", this.goEasy);
				if (uid > 0 && this.goEasy !== undefined) {

					this.$http.get('/client/user/account/info', {}).then(res => {
						this.goEasy.connect({
							id: uid,
							data: {
								name: res.Nickname,
								avatar: res.AvatarImg
							},
							onSuccess: () => {
								console.log('GoEasy connect successfully.')
							},
							onFailed: (error) => {
								console.log('Failed to connect GoEasy, code:' + error.code +
									',error:' + error
									.content);
							},
							onProgress: (attempts) => {
								console.log('GoEasy is connecting', attempts);
							}
						});
					});

					//订阅Goeasy消息
					this.goEasy.pubsub.subscribe({
						channel: "user" + uid,
						onMessage: function(message) {
							console.log("Channel:" + message.channel + " content:" +
								message.content);
						},
						onSuccess: function() {
							console.log("Channel订阅成功。");
						},
						onFailed: function(error) {
							console.log("Channel订阅失败, 错误编码：" + error.code + " 错误信息：" +
								error.content)
						}
					});
				}
			},
			checkArguments() {
				/// http://www.html5plus.org/doc/zh_cn/runtime.html

				// 得到启动方式
				// 处理打开的参数
				try {
					var launcher = plus.runtime.launcher;
					var args = plus.runtime.arguments;
					const tid = args.slice(args.indexOf('=') + 1, args.indexOf('&'))
					const type = args.slice(args.indexOf('&') + 6)
					if (type == 1) {
						uni.navigateTo({
							url: "/pages/article/detail/index?tid=" + tid
						})
					}
					// 使用API获取打开app的参数： plus.runtime.arguments
					// 然后在解析参数 根据解析后的参数跳转到对应的URL

				} catch (e) {
					console.log('解析参数 页面跳转失败' + e);
				}
			},
			// initJG() {
			// 	let that = this;
			// 	jpushModule.initJPushService();
			// 	jpushModule.addConnectEventListener(result => {
			// 		let connectEnable = result.connectEnable
			// 		uni.$emit('connectStatusChange', connectEnable)
			// 	});

			// 	jpushModule.getRegistrationID(result => {
			// 		let registerID = result.registerID;
			// 		that.$http.post('/client/user/account/device/register', {
			// 			registerId: registerID
			// 		}).then(res => {});
			// 	});
			// },
			changLang() {
				let language = uni.getSystemInfoSync().language || '';
				let lang = language.split('-')[0] || '';
				if (lang == 'zh') {
					this.$i18n.locale = '中文';
					uni.setStorageSync('lang', '中文');
				} else if (lang == 'ru') {
					this.$i18n.locale = 'русский';
					uni.setStorageSync('lang', 'русский');

					this.updateWords.tips = 'Обновить подсказку';
					this.updateWords.new = 'новая версия ';
					this.updateWords.isUpdate = ' Обновить?';
					this.updateWords.confirmText = 'Обновить';
					this.updateWords.cancelText = 'Не сейчас';
					this.updateWords.prepare = 'будьте добры, подождите.';
					this.updateWords.download = 'загрузка';
					this.updateWords.connected = 'подключен к серверу';
					this.updateWords.success = 'Загрузка завершена';
					this.updateWords.failed1 = 'Ошибка обновления 01';
					this.updateWords.failed2 = 'Ошибка обновления 02';
					this.updateWords.failed3 = 'Ошибка обновления 03';
				} else {
					this.$i18n.locale = 'English';
					uni.setStorageSync('lang', 'English');

					this.updateWords.tips = 'Update tips';
					this.updateWords.new = 'New version ';
					this.updateWords.isUpdate = ' found, update?';
					this.updateWords.confirmText = 'update';
					this.updateWords.cancelText = 'not now';
					this.updateWords.prepare = 'Preparing environment, please wait';
					this.updateWords.download = 'downloading';
					this.updateWords.connected = 'connected to the server';
					this.updateWords.success = 'download success';
					this.updateWords.failed1 = 'Update failed 01';
					this.updateWords.failed2 = 'Update failed 02';
					this.updateWords.failed3 = 'Update failed 03';
				}
			},
			//更改tabar通知红点状态
			changeNotidyRedStatus(state, status) {
				let notidyTimRedStatus = uni.getStorageSync('notidyTimRedStatus');
				let notidyMsgRedStatus = uni.getStorageSync('notidyMsgRedStatus');
				console.log("notidyTimRedStatus", notidyTimRedStatus)
				console.log("notidyMsgRedStatus", notidyMsgRedStatus)
				if (notidyTimRedStatus || notidyMsgRedStatus) {
					uni.showTabBarRedDot({
						index: 2,
					});
				} else if (!notidyTimRedStatus && !notidyMsgRedStatus) {
					uni.hideTabBarRedDot({
						index: 2,
					});
				}
			},
			initSQLiteCreateTable() {

				let uid = this.vuex_user.uid || 0;
				if (uid > 0) {
					let dbname = sqliteSQL.db.dbName
					let path = '_doc/' + uid + '.db'
					let tableDescribe = sqliteSQL.createTableSql.describe || []
					let createTableSql = []
					for (let i = 0; i < tableDescribe.length; i++) {
						let sql = tableDescribe[i].join("\n")
						createTableSql.push(sql)
					}

					//检查是否打开了
					let isOpen = db.isOpenDB(dbname, path)
					if (isOpen) {
						plus.sqlite.executeSql({
							name: dbname,
							sql: createTableSql,
							success: async (e) => {
								await db.closeDB(dbname)
							},
							fail: async (e) => {
								console.log(e);
								await db.closeDB(dbname)
							}
						})

					} else {
						plus.sqlite.openDatabase({
							name: dbname,
							path: path,
							success: function(res) {
								plus.sqlite.executeSql({
									name: dbname,
									sql: createTableSql,
									success: async (e) => {
										await db.closeDB(dbname)
									},
									fail: async (e) => {
										await db.closeDB(dbname)
									}
								})
							},
							fail: async (e) => {
								console.log('打开数据库失败： ' + JSON.stringify(e))
							}
						});
					}
				}
			},
		},
	}
</script>

<style lang="scss">
	@import './static/iconfont/iconfont.css';
	@import './static/text/text.scss';
	@import "./uni_modules/vk-uview-ui/index.scss";
	html,
	body {
		height: 100%;
		width: 100%;
		background-color: #fefefe;
	}

	page {
		height: 100%;
		background-color: #fefefe;
	}

	.lang-form {
		padding: 0 30rpx;
		margin-bottom: 60rpx;

		&-cell {
			position: relative;
			padding: 45rpx 0 25rpx;
			justify-content: space-between;
			border-bottom: 1rpx solid #D2D2D2;
			uni-radio .uni-radio-input {
				border-color: #FFFFFF;
			}

			uni-radio .uni-radio-input.uni-radio-input-checked:before {
				color: #007aff;
				font-size: 24px;
				background-color: #FFFFFF;
				border-color: #FFFFFF;
			}
		}
	}

	uni-tabbar .uni-tabbar__reddot {
		width: 8px;
		height: 8px;
	}

	.uni-video-container,
	.uni-video-video {
		background-color: #FFFFFF;
	}

	.ui-row {
		flex-direction: row;
	}

	.ui-column {
		flex-direction: column;
	}

	.ui-col {
		flex: 1;
	}

	.ui-center {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif*/
		align-items: center;
		justify-content: center;
	}

	.ui-row-center {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif*/
		justify-content: center;
	}

	.ui-row-between {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif*/
		flex-direction: row;
		justify-content: space-between;
	}

	.ui-col-center {
		/* #ifndef APP-PLUS-NVUE */
		display: flex;
		/* #endif*/
		align-items: center;
	}

	.ui-strong {
		font-weight: 700;
	}

	.ui-txt-white {
		color: #fff;
	}

	.ui-txt-mute {
		color: #666;
	}

	.ui-txt-info {
		color: #999;
	}

	.ui-font-size24 {
		font-size: 48rpx;
	}

	.ui-font-size20 {
		font-size: 40rpx;
	}

	.ui-font-size16 {
		font-size: 32rpx;
	}

	.ui-font-size14 {
		font-size: 28rpx;
	}

	.ui-font-size13 {
		font-size: 26rpx;
	}

	.ui-font-size12 {
		font-size: 24rpx;
	}

	.edit-cell_item--textarea .uni-textarea-wrapper {
		height: 180rpx;
		overflow: hidden;
	}
</style>